/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lin.linker.redcell;

import java.util.*;
import java.io.*;
import java.io.Console.*;
import java.io.ByteArrayInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author linker
 */
public final class Table {

    public Table() {
        table = new TreeMap();

    }

    public Table(Table t) {
        table = t.getMap();
    }

    public TreeMap getMap() {
        return table;
    }

    public Object setKeyValue(Object k, Object v) {
        if (v == null) {
            return table.remove(k);
        } else {
            return table.put(k, v);
        }
    }

    public String dumpTable() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        this.dumpTableLevel(baos, 0);
        String s = "";
        try {
            s = baos.toString("UTF-8");
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Table.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            return s;
        }
    }

    public void dumpTableLevel(ByteArrayOutputStream baos, int level) {
        String prefix = "";
        for (int i = 0; i < level; i++) {
            prefix += INDENT;
        }
        try {
            baos.write("{".getBytes());
            int IntKey = 0;
            boolean flag = true;
            for (Object entry : this.getMap().entrySet()) {
                if (entry instanceof Map.Entry) {
                    if (flag) {
                        flag = false;
                    } else {
                        baos.write(",".getBytes());
                    }
                    //System.out.printf("%s",((Map.Entry)entry).getKey());
                    baos.write("\"".getBytes());
                    baos.write(((Map.Entry) entry).getKey().toString().getBytes("UTF-8"));
                    baos.write("\":".getBytes());
                    if (((Map.Entry) entry).getValue() instanceof Table) {
                        System.out.printf("%d ",level);
                        ((Table)((Map.Entry) entry).getValue()).dumpTableLevel(baos,level+1);

                    } else {
                        baos.write("\"".getBytes());
                        baos.write(((Map.Entry) entry).getValue().toString().getBytes("UTF-8"));
                        baos.write("\"".getBytes());
                    }
                }
            }

            baos.write("}".getBytes());
        } catch (IOException ex) {
            Logger.getLogger(Table.class.getName()).log(Level.SEVERE, null, ex);
        }


    }
    private TreeMap<Object, Object> table;
    private static final String INDENT = "  ";
}
